
//设备登录
let login = require("./login.js");
login.deviceLogin()
let config = require("./config.js");

if(!requestScreenCapture()){
    toast("请求截图失败,即将退出");
    exit();
}
var storage = storages.create("com.axie.tools.storages");
var date = storage.get("date")
var today = date_form();
if(date != today){
    storage.put("date", today)
    storage.put("win_count", 0)
}
sleep(1000);
toast("请进入pve界面，选择想要打的关卡");
sleep(5000);

var width = Math.max(device.width, device.height)
var height = Math.min(device.width, device.height)
var scaleWidth = width / 2160
var scaleHeight = height / 1080
var img = captureScreen();
if(img.width < img.height){
    img.recycle()
    toast("请在横屏下运行，即将退出")
    exit()
}
img.recycle()
toast("开始运行了");
while(true){
    while(true){
        var img = captureScreen();
        click(width-100,height-30);
        //判断是否有弹窗
        var templ = images.read("./img/ok.png");
        var point = myFindImage(img,templ,0.6,[width/4,height/3,2*width/4,height/3])
        templ.recycle();
        if(point){
            click(point.x+40,point.y+20);
            sleep(2000)
            continue
        }
        //判断是否成功加载
        var templ = images.read("./img/disconnect.png");
        var point = myFindImage(img,templ,0.6,[0,height/2,width/2,height/2])
        templ.recycle();
        if(point){
            img.recycle();
            click(75,87);
            sleep(1000)
            click(1560,610);
            sleep(4000)
            continue
        }
        // 判断是否要开始pve
        var templ = images.read("./img/templ_start_pve.png");
        var point = myFindImage(img,templ,0.5,[width/2,3*height/4,width/2,height/4])
        templ.recycle();
        if(point){
            var win_count = storage.get("win_count")
            //判断体力，等级，和pve奖励是否已全部获取
            var slpimg = images.read("./img/slp_50.png"); //奖励领取
            var lever = images.read("./img/lever_25.png"); //等级判断
            var power = images.read("./img/power_0.png"); //体力判断
            var pslp = myFindImage2(img,slpimg,0.97,[125, 528, 27, 20])
            var plever = myMatchTemplate2(img,lever,0.93,[800, 700, 1100, 200])
            var ppower = myFindImage2(img,power,0.97,[285, 33, 15, 18])
            console.log(plever)
            if( pslp){
                if(plever.matches.length>2|| ppower ||win_count >20){
                    toast("奖励已全部获取，即将结束");
                    //请求接口，提交数据
                    back()
                    sleep(2000)
                    img.recycle()
                    //识别账号
                    var img = captureScreen();
                    var clip2 = images.clip(img, 120, 40,220,45); 
                    var acount = Ttshitu_Ocr_FindWord(1001,images.toBase64(clip2))
                    img.recycle(); 
                    clip2.recycle(); 
    
                    //识别slp
                    click(620,950);
                    sleep(2000)
                    var img = captureScreen();
                    var clip2 = images.clip(img, 240, 450,180,40)
                    var slp = Ttshitu_Ocr_FindWord(1001,images.toBase64(clip2))
                    img.recycle(); 
                    clip2.recycle(); 
                    lever.recycle()
                    slpimg.recycle()
                    PushData(acount,slp)
                    back()
                    CloseApp('Axie Infinity')
                    home()
                    engines.stopAll();
                    exit();
                }
            }
            img.recycle();
            lever.recycle()
            slpimg.recycle()
            toast("开始pve模式");
            click(point.x+200*scaleWidth,point.y+50*scaleHeight);
            sleep(8000)
            continue
        }
        // 判断是否输了
        //console.log("判断是否输了")
        var templ = images.read("./img/templ_fail1.png");
        var point = myFindImage(img,templ,0.5,[0,height/3,width,height/3])
        templ.recycle();
        if(point){
            img.recycle();
            toast("输了，即将返回开始页");
            //console.log("输了，即将返回开始页")
            //返回pve开始页面
            a = Math.round(Math.random()*10+800)
            b = Math.round(Math.random()*10+400)
            click(width-10,height-10);
            sleep(1000)
            sleep(Math.round(Math.random()*500+3000))
            click(width-10,height-10);
            sleep(5000)
            click(width-10,height-10);
            break
        }
        
        // 判断是否赢了
        //console.log("判断是否赢了")
        var templ = images.read("./img/templ_success1.png");
        var point = myFindImage(img,templ,0.5,[0,height/3,width,height/3])
        templ.recycle();
        if(point){
            img.recycle();
            toast("赢了，即将返回开始页");
            var win_count = storage.get("win_count")
            storage.put("win_count", win_count+1)
            //console.log("赢了，即将返回开始页")
            //返回pve开始页面
            a = Math.round(Math.random()*10+1100)
            b = Math.round(Math.random()*10+700)
            click(width-10,height-10);
            sleep(Math.round(Math.random()*500+1000))
            click(width-10,height-10);
            sleep(5000)
            click(width-10,height-10);
            break
        }
        sleep(1000)
        // 判断是否该出牌 end turn
        //console.log("判断是否要出牌了")
         var templ = images.read("./img/end_turn.png");
         var point = myFindImage(img,templ,0.5,[3*width/4,2*height/3,width/4,height/3])
         templ.recycle();
        if(point){
            toast("开始出牌了");
            //console.log("开始出牌了")
            //返回pve开始页面
            //console.log("开始识别0能量卡牌")
            var templ = images.read("./img/card_power_0.png");
            var p = myMatchTemplate(img,templ,0.65,[0,3*height/4,width,height/4])
            templ.recycle();
            if(p){
                p.matches.forEach(match => {
                    a = Math.round(Math.random()*10+5);
                    b = Math.round(Math.random()*10+5);
                    if(match.point.x>1100*scaleWidth){
                        swipe(match.point.x+5*scaleWidth, match.point.y+5*scaleHeight, match.point.x-300*scaleWidth, match.point.y-Math.round(Math.random()*10+210)*scaleHeight, a*50)
                    }else{
                        swipe(match.point.x+5*scaleWidth, match.point.y+5*scaleHeight, match.point.x+300*scaleWidth, match.point.y-Math.round(Math.random()*10+200)*scaleHeight, b*50)
                    }
                    sleep(Math.round(Math.random()*100+30))
                });
            }
            
            // var templ1 = images.read("/sdcard/1/card_power_1.png");
            // var p1 = images.matchTemplate(img, templ1, {
            //     max: 10
            // });
            //console.log("开始识别1能量卡牌")
            var json = get_point_hurt(img,"./img/card_power_1.png")
            // console.log(json )
            if(json){
                for( var i = 0;i<json.length;i++){
                    a = Math.round(Math.random()*10+5);
                    b = Math.round(Math.random()*10+5);
                    var match = json[i]
                    // console.log(match )
                    //toast("point = " + match.point + ", similarity = " + match.similarity);
                    if(match.x>width/2){
                        swipe(match.x+5*scaleWidth, match.y+5*scaleHeight, match.x-300*scaleWidth, match.y-Math.round(Math.random()*10+210)*scaleHeight, a*50)
                    }else{
                        swipe(match.x+5*scaleWidth, match.y+5*scaleHeight, match.x+300*scaleWidth, match.y-Math.round(Math.random()*10+200)*scaleHeight, b*50)
                    }
                    sleep(Math.round(Math.random()*100+30))
                }
            }
            click(point.x+40*scaleWidth,point.y+15*scaleHeight);
            sleep(Math.round(Math.random()*1000+100))
            img.recycle();
        }
        
        templ.recycle();
        img.recycle();
        
        // click(width-100,height-30);
        toast("对局等待中。。。")
        //console.log("对局等待中。。。")
        //console.log("==============================")
        sleep(4*1000)
    }
    
    toast("即将开始下一轮");
    sleep(1000)
}

//找单张图
function myFindImage(img,templ,threshold,region){
    var templ1 = images.scale(templ, scaleWidth, scaleHeight)
    var p = findImage(img, templ1,{
        region: region,
        threshold: threshold,
    });
    templ1.recycle();
    if(p){
        return p
    }
    var p1 = findImage(img, templ,{
        region: region,
        threshold: threshold,
    });
    return p1
}
//找多张图
function myMatchTemplate(img,templ,threshold,region){
    var templ1 = images.scale(templ, scaleWidth, scaleHeight)
    let result = images.matchTemplate(img, templ1, {
        max: 10,
        region: region,
        threshold: threshold
    });
    templ1.recycle();
    if(result){
        return result
    }
    let result1 = images.matchTemplate(img, templ, {
        max: 10,
        region: region,
        threshold: threshold
    });
    return result1
}

//排序
function f(a, b) {
    var a1 = Number(a.h);
    var b1 = Number(b.h);
    if(a1>b1){
        return -1;
    }else if(a1<b1){
        return 1;
    }else{
        return 0;
    }
}

//处理出牌策略，目前按伤害最大
function strategy(data){
    data.sort(f)
    return data
}

//根据截图找坐标并识别最大伤害
function get_point_hurt(img,trmpl_path){
    var templ = images.read(trmpl_path);
    var p = myMatchTemplate(img,templ,0.6,[0,3*height/4,width,height/4])
    if(p){
        p.matches.forEach((match,index) => {
            app.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,android.net.Uri.fromFile(java.io.File('./img/test5555.png'))));
            if (index==0) {
                let sav = images.clip(img, match.point.x-23*scaleWidth, match.point.y+25*scaleHeight,40*scaleWidth,55*scaleHeight);
                images.save(sav, "./img/test5555.png");
                sav.recycle(); 
            }else{
                let clip = images.clip(img, match.point.x-23*scaleWidth, match.point.y+25*scaleHeight,40*scaleWidth,55*scaleHeight);
                let sav = images.read("./img/test5555.png");
                let sav1 = images.concat(sav, clip,"bottom") 
                images.save(sav1, "./img/test5555.png");
                sav.recycle(); 
                sav1.recycle(); 
                clip.recycle()
            }  
        });
        
    }

    //二值化
    templ.recycle();
    img.recycle();
    
    var hurt_shield = BaiDu_Ocr_FindWord("./img/test5555.png")
    var array = []; 

    if(hurt_shield&& hurt_shield.length ==p.matches.length ) {
        for( var i = 0;i<p.matches.length;i++){
            var item = {
                x: p.matches[i].point.x,
                y: p.matches[i].point.y, 
                h: hurt_shield[i].words
            }
            array.push(item);
        }
        return strategy(array)
    }else{
        for( var i = 0;i<p.matches.length;i++){
            var item = {
                x: p.matches[i].point.x,
                y: p.matches[i].point.y, 
            }
            array.push(item);
        }
        return array
    }
    
}

 
/**
 * @function BaiDu_Ocr_FindWord 百度识别查找文字，找到返回true,失败返回false.
 * @param str 图片路径。
  */
 function BaiDu_Ocr_FindWord(str){
    try {
        http.__okhttp__.setTimeout(5000);
        //注册百度云识别时给的,可以登录百度智能云在创建应用里面查看到。
        var API_Key = config.getKey("baidu_api_key")
        //注册百度云识别时给的,可以登录百度智能云在创建应用里面查看到。
        var Secret_Key = config.getKey("baidu_secret_Key");
        //access_token获取地址,向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求（推荐使用POST），并在URL中带上以下参数：
        //access_token = http.get("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=YIKKfQbdpYRRYtqqTPnZ5bCE&client_secret=hBxFiPhOCn6G9GH0sHoL0kTwfrCtndDj").body.json().access_token;

        var 提交地址 = "https://aip.baidubce.com/oauth/2.0/token"
        var token_Res = http.post(提交地址, {
            grant_type: "client_credentials",
            client_id: API_Key,
            client_secret: Secret_Key,
        });
        var token = token_Res.body.json().access_token
        //我这个利用模拟器在测试，因为AUTOJS的截图在模拟器上老出错所有改用Shell截图
        //读取图片
        var img = images.read(str)
        //转化成基于64的图片
        var imag64 = images.toBase64(img, "png", 100); 
        img.recycle();
        var Common_Ocr_Url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"; //普通文字识别,每天可用5000次。
        var ocr_Res = http.post(Common_Ocr_Url, {
            headers: {
                "Content - Type": "application/x-www-form-urlencoded" //连接的请求方式,一般是'content-type': 'application/json',
            },
            access_token: token,
            image: imag64,
        })
        return ocr_Res.body.json().words_result;
    } catch(e) {
        return 
    }
    
 }



/**
 * @function Ttshitu_Ocr_FindWord 图鉴识别文字，1001纯数字，7无感学习.
 * @param str 图片路径。
  */
 function Ttshitu_Ocr_FindWord(typeid,imag64){
    try {
        http.__okhttp__.setTimeout(20000);
        var username = config.getKey("ttshitu_name")
        var password = config.getKey("ttshitu_pass")

        var Url = "http://api.ttshitu.com/predict	"; //普通文字识别,每天可用5000次。
        var ocr_Res = http.post(Url, {
            headers: {
                "Content - Type": "application/json;charset=UTF-8" //连接的请求方式,一般是'content-type': 'application/json',
            },
            username: username,
            password:password,
            typeid:typeid,
            image: imag64,
        })
        if (ocr_Res.body.json().code==0){
            return ocr_Res.body.json().data.result;
        }else{
            return 
        }
        
    } catch(e) {
        return 
    }
    
 }


//找单张图
function myFindImage2(img,templ,threshold,region){
    var p1 = findImage(img, templ,{
        region: region,
        threshold: threshold,
    });
    return p1
}


//找多张图
function myMatchTemplate2(img,templ,threshold,region){
    let result1 = images.matchTemplate(img, templ, {
        max: 10,
        region: region,
        threshold: threshold
    });
    return result1
}

function date_form(time) {
    if (time) {
        return new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date(time));
    } else {
        return new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }
}




function CloseApp(packageName) {
     
    var name = getPackageName(packageName); 
    if(!name){
     
        if(getAppName(packageName)){
     
            name = packageName;
        }else{
     
            return false;
        } 
    }
    app.openAppSetting(name);
    text(app.getAppName(name)).waitFor();  
    let is_sure = textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOne();
    if (is_sure.enabled()) {
     
        textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOne().click();
        textMatches(/(.*确.*|.*定.*)/).findOne().click();
        log(app.getAppName(name) + "应用已被关闭");
        sleep(1000);
        back();
    } else {
     
        log(app.getAppName(name) + "应用不能被正常关闭或不在后台运行");
        back();
    }
}



//提交数据
function PushData(name,amount){
    try {
        http.__okhttp__.setTimeout(15000);
        var Url = "http://49.235.204.147:9006/v1/slp/daily"; 
        var ocr_Res = http.post(Url, {
            headers: {
                "Content - Type": "application/json;charset=UTF-8" //,
            },
            name: name,
            slp:amount,
        })
        
    } catch(e) {
        return 
    }
    
 }

